package com.example.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.file.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity{
	private File path=null;
	private File[] filelist;
	private boolean firstActivity=false;
	private long exitTime=0;
	private ListView listView;
	private List<Map<String,Object>> mdata;
	private Map<String, Object> isCheck=new HashMap<String,Object>();
	private int checkBoxVisable=View.GONE;
	private int activityNum=0;
	private CheckBox selectAll;
	private Handler handler=new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listview);
		listView=(ListView) findViewById(R.id.listview);
		try{
			path=(File) this.getIntent().getExtras().get("path");
			activityNum=this.getIntent().getExtras().getInt("activityNum");
			activityNum++;
		}
		catch(Exception ex){
			firstActivity=true;
			path=Environment.getExternalStorageDirectory();//获取sdcard路径
		}
		filelist=path.listFiles();//获取path路径下的文件
		filelist=groupbyname(filelist);//按名称排序
		mdata=new ArrayList<Map<String,Object>>();
	    for(int i=0;i<filelist.length;i++){
	        Map<String,Object> map=new HashMap<String,Object>();
	        if(filelist[i].isDirectory()){
	        	map.put("img", R.drawable.floder);
	        }else{
	        	map.put("img",R.drawable.file);
	        }
	       	map.put("name", filelist[i].getName());
	       	map.put("fileType", getPostfix(filelist[i]));
	       	mdata.add(map);
	    }
	    //初始化isCheck
	    for(int i=0;i<filelist.length;i++){
	    	isCheck.put(""+i, false);
	    }
	    if(filelist.length==0){//如果文件夹内无文件
	    	Toast.makeText(MainActivity.this, "文件夹为空", Toast.LENGTH_LONG).show();
	    }
	    listView.setAdapter(baseAdapter);
	    listView.setOnItemClickListener(browseState);
	    listView.setOnItemLongClickListener(itemLongClickListener);
	    TextView t=(TextView) findViewById(R.id.path);
	    t.setText(path.toString());
	    ImageButton delete=(ImageButton) findViewById(R.id.delete);
	    ImageButton create=(ImageButton) findViewById(R.id.create);
	    ImageButton manage=(ImageButton) findViewById(R.id.manage);
	    selectAll=(CheckBox) findViewById(R.id.selectAll);
	    delete.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		delete();
	    	}
	    });
	    create.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		create();
	    	}
	    });
	    manage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				attributes();
			}
		});
	    selectAll.setOnCheckedChangeListener(selectAllListener);
	}
	
	OnItemClickListener browseState=new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
			if(filelist[position].isDirectory()){
				Intent intent=new Intent(MainActivity.this,MainActivity.class);
				intent.putExtra("path", new File(path.toString()+"/"+filelist[position].getName()));
				intent.putExtra("activityNum", activityNum);
				startActivity(intent);
			}else{
				//打开文件
				String type=getType(filelist[position]);
				Intent intent=new Intent("android.intent.action.VIEW");
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(Uri.fromFile(filelist[position]), type);
				startActivity(intent);
			}
		}
	};
	OnItemClickListener modifiedState=new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
			if (checkBox.isChecked()) {
				checkBox.setChecked(false);
			} else {
				checkBox.setChecked(true);
			}
		}
	};
	OnItemLongClickListener itemLongClickListener=new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> parent,
				View view, int position, long id) {
			checkBoxVisable=View.VISIBLE;
			isCheck.put(""+position, true);
			listView.setOnItemClickListener(modifiedState);
			listView.setOnItemLongClickListener(null);
			baseAdapter.notifyDataSetChanged();
			return true;
		}
	};
	BaseAdapter baseAdapter=new BaseAdapter() {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater=getLayoutInflater();
			View v=inflater.inflate(R.layout.alist, null);
			ImageView img=(ImageView) v.findViewById(R.id.image);
			TextView name=(TextView) v.findViewById(R.id.name);
			TextView fileType=(TextView) v.findViewById(R.id.fileType);
			img.setImageResource((int) mdata.get(position).get("img"));
			name.setText(mdata.get(position).get("name").toString());
			if(mdata.get(position).get("fileType").toString().equals("")){
				fileType.setVisibility(View.GONE);
			}else{
				fileType.setText(mdata.get(position).get("fileType").toString());
			}
			CheckBox box=(CheckBox) v.findViewById(R.id.checkBox1);
			box.setTag(position);
			box.setOnCheckedChangeListener(checkBoxListener);
			if((boolean) isCheck.get(""+position)==true){
				box.setChecked(true);
			}
			box.setVisibility(checkBoxVisable);
			return v;
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}
		@Override
		public Object getItem(int position) {
			return null;
		}
		@Override
		public int getCount() {
			return filelist.length;
		}
	};
	OnCheckedChangeListener checkBoxListener=new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			isCheck.put(buttonView.getTag().toString(), isChecked);
			if (!isChecked) {
				((View) buttonView.getParent()).setBackgroundColor(Color.argb(0,255,255,255));
			} else {
				((View) buttonView.getParent()).setBackgroundColor(Color.argb(255, 47, 118, 247));
			}
			boolean flag=false; //用于判断是否有checkBox选中
			for(int i=0;i<filelist.length;i++){
				if((boolean) isCheck.get(""+i)==true){
					flag=true;
					break;
				}
			}
			if(flag==false){//没有checkBox选中
				checkBoxVisable=View.GONE;
				listView.setOnItemClickListener(browseState);
				listView.setOnItemLongClickListener(itemLongClickListener);
				selectAll.setChecked(false);
				baseAdapter.notifyDataSetChanged();
			}
		}
	};
	OnCheckedChangeListener selectAllListener=new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if(isChecked){
				for(int i=0;i<filelist.length;i++){
					isCheck.put(""+i, true);
				}
				listView.setOnItemClickListener(modifiedState);
				listView.setOnItemLongClickListener(null);
				checkBoxVisable=View.VISIBLE;
			}else{
				for(int i=0;i<filelist.length;i++){
					isCheck.put(""+i, false);
				}
				listView.setOnItemClickListener(browseState);
				listView.setOnItemLongClickListener(itemLongClickListener);
				checkBoxVisable=View.GONE;
			}
			baseAdapter.notifyDataSetChanged();
		}
	};
	public static File[] groupbyname(File[] file){//按名称排序
		if(file.length==0){return file;}
		String tmp=null;
		File filetmp=null;
		int length=file.length;
		File[] result = new File[length];
		String[] DirectoryName = new String[length];
		String[] FileName = new String[length];
		int num=0;
		for(int i=0;i<file.length;i++){//文件和文件夹分类
			if(file[i].isDirectory()){
				result[num]=file[i];
				DirectoryName[num]=result[num].getName().toUpperCase();
				num++;
			}else{
				length--;
				result[length]=file[i];
				FileName[length]=result[length].getName().toUpperCase();
			}
		}
		for(int i=0;i<num;i++){//文件夹排序
			for(int j=i+1;j<num;j++){
				if(DirectoryName[i].compareTo(DirectoryName[j])>0){
					tmp=DirectoryName[i];
					DirectoryName[i]=DirectoryName[j];
					DirectoryName[j]=tmp;
					filetmp=result[i];
					result[i]=result[j];
					result[j]=filetmp;
				}
			}
		}
		for(int i=num;i<file.length;i++){//文件排序
			for(int j=i+1;j<file.length;j++){
				if(FileName[i].compareTo(FileName[j])>0){
					tmp=FileName[i];
					FileName[i]=FileName[j];
					FileName[j]=tmp;
					filetmp=result[i];
					result[i]=result[j];
					result[j]=filetmp;
				}
			}
		}
		return result;
	}
	public String getType(File file){//获取文件类型
		String type = getPostfix(file);
		switch (type.toLowerCase()) {
		case "png":
			type="image/png";
			break;
		case "jpg":
			type="image/jpeg";
			break;
		case "jpeg":
			type="image/jpeg";
			break;
		case "txt":
			type="text/plain";
			break;
		case "html":
			type="text/html";
			break;
		case "pdf":
		    type="application/pdf";
		    break;
		case "mp3":
			type="audio/*";
			break;
		case "mp4":case "rmvb":case "mkv":case "flv":
		case "3gp":case "avi":case"wmv":
			type="video/*";
			break;
		default:
			type="*/*";
			break;
		}
		return type;
	}
	public static String getPostfix(File file){//获取后缀
		String type = "";
		if(file.isDirectory()){ return "";}
		char[] name=file.getName().toString().toCharArray();
		for(int i=file.getName().length()-1;i>=0;i--){
			if(name[i]=='.'){
				break;
			}else{
				type=name[i]+type;
			}
		}
		if(file.getName().indexOf(".")<0 || type.length()>6){
			type=" ? 文件";
		}
		return type;
	}
	public ArrayList<Object> getSelect(){//获取选中文件
		ArrayList<Object> a=new ArrayList<Object>();
		for(int i=0;i<filelist.length;i++){
			if((boolean)isCheck.get(""+i)==true){
				a.add(i);
			}
		}
		return a;
	}
	
	public void create(){
		final EditText t=new EditText(this);
		AlertDialog.Builder alert=new Builder(this);
		alert.setTitle("新建文件/文件夹");
		t.setPadding(10, 20, 10, 0);
		alert.setView(t);
		alert.setPositiveButton("新建文件",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(t.getText().toString().equals("")==false){
					File f=new File(path.toString()+"/"+t.getText().toString());
					try {
						f.createNewFile();
						refresh();
					} catch (IOException e) {
						Toast.makeText(MainActivity.this, "创建失败", Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(MainActivity.this, "输入文件名", Toast.LENGTH_SHORT).show();
					create();
				}
			}
		});
		alert.setNeutralButton("新建文件夹", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(t.getText().toString().equals("")==false){
					File f=new File(path.toString()+"/"+t.getText().toString());
					if(f.mkdir()){
						refresh();
					}else{
						Toast.makeText(MainActivity.this, "创建失败", Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(MainActivity.this, "输入文件名", Toast.LENGTH_SHORT).show();
					create();
				}
			}
		});
		alert.setNegativeButton("取消", null);
		alert.create().show();
	}
	public void delete(){
		final ArrayList<Object> select=getSelect();
		if(select.size()!=0){
			AlertDialog.Builder alert=new Builder(this);
			alert.setTitle("Delete");
			alert.setMessage("确认删除"+select.size()+"个文件？");
			alert.setPositiveButton("确定",new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					for(int i=0;i<select.size();i++){
						if(filelist[(int)select.get(i)].isDirectory()){
							deleteDir(filelist[(int)select.get(i)]);
						}else if(!filelist[(int)select.get(i)].delete()){
							Toast.makeText(MainActivity.this, filelist[(int)select.get(i)].getName()+"删除失败", Toast.LENGTH_SHORT).show();
						}
					}
					refresh();
					if(filelist.length==0){
						checkBoxVisable=View.GONE;
						listView.setOnItemClickListener(browseState);
						listView.setOnItemLongClickListener(itemLongClickListener);
						for(int i=0;i<filelist.length;i++){
							isCheck.put(""+i, false);
						}
						CheckBox selectAll=(CheckBox) findViewById(R.id.selectAll);
						selectAll.setChecked(false);
						baseAdapter.notifyDataSetChanged();
					}
				}
			});
			alert.setNegativeButton("取消", null);
			alert.create().show();
		}else{
			Toast.makeText(MainActivity.this, "你没选中任何文件", Toast.LENGTH_SHORT).show();
		}
	}
	public void deleteDir(File file){
		File[] childFiles = file.listFiles();
		if(childFiles==null||childFiles.length==0){
			file.delete();
			return;
		}
		for(int i=0;i<childFiles.length;i++){
			deleteDir(childFiles[i]);
		}
		file.delete();
	}
	public void rename(){
		ArrayList<Object> select=getSelect();
		if(select.size()==0){
			Toast.makeText(MainActivity.this, "你没选中任何文件", Toast.LENGTH_SHORT).show();
			return ;
		}
		if(select.size()==1){
			final EditText t=new EditText(this);
			final int i=(int)select.get(0);
			t.setText(filelist[i].getName());
			AlertDialog.Builder alert=new Builder(this);
			alert.setTitle("重命名");
			alert.setView(t);
			try{
				t.setSelection(0,t.getText().toString().indexOf("."));
			}catch(Exception e){
				t.setSelection(0,filelist[i].getName().length());
			}
			alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(t.getText().toString().trim().equals("")==false){
						File targetFileName=new File(path, t.getText().toString());
						boolean isOK=filelist[i].renameTo(targetFileName);
						if(isOK==false){
							Toast.makeText(MainActivity.this, "重命名失败", Toast.LENGTH_SHORT).show();
							targetFileName.delete();
						}
						refresh();
					}
				}
			});
			alert.setNegativeButton("取消", null);
			alert.create().show();
		}else{
			int[] s = new int[select.size()];
			Intent reNameActivity=new Intent(MainActivity.this,rename.class);
			for(int i=0;i<select.size();i++){
				s[i]=(int) select.get(i);
			}
			reNameActivity.putExtra("path", path);
			reNameActivity.putExtra("select", s);
			startActivity(reNameActivity);
		}
	}
	
	
	
	Thread getSize;
	View attributesView;
	private static boolean stopThread=false;
	private static long fileByteSize=0;
	public void attributes(){
		attributesView=getLayoutInflater().inflate(R.layout.file_attributes, null);
		final ArrayList select=getSelect();
		if(select.size()==0) {
			Toast.makeText(MainActivity.this, "你没选中任何文件", Toast.LENGTH_SHORT).show();
			return;
		}
		AlertDialog.Builder alert=new Builder(this);
		alert.setTitle("属性");
		alert.setView(attributesView);
		alert.setNegativeButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				stopThread=true;
				while(getSize.isAlive()){}//等待线程结束
				stopThread=false;
				handler.removeCallbacks(runnable);
				fileByteSize=0;
			}
		});
		alert.setCancelable(false);
		
		alert.create().show();
		TextView name=(TextView) attributesView.findViewById(R.id.fileName);
		TextView size=(TextView) attributesView.findViewById(R.id.size);
		TextView position=(TextView) attributesView.findViewById(R.id.position);
		TextView type=(TextView) attributesView.findViewById(R.id.type);
		if(select.size()==1){
			name.setText(filelist[(int) select.get(0)].getName());
			size.setText("0 B");
			position.setText(path.toString());
			if(filelist[(int) select.get(0)].isDirectory()){type.setText("文件夹");}
			else{type.setText(getPostfix(filelist[(int) select.get(0)]));}
			getSize=new Thread(new Runnable() {
				@Override
				public void run() {
					try{
						getFileSzie(filelist[(int) select.get(0)]);
					}catch(RuntimeException e){
						//
					}
				}
			});
		}else{
			type.setText("");
			TextView t=(TextView) attributesView.findViewById(R.id.textView1);
			t.setVisibility(View.INVISIBLE);
			name.setText(select.size()+" 个文件");
			position.setText(path.toString());
			getSize=new Thread(new Runnable() {
				@Override
				public void run() {
					try{
						for(int i=0;i<select.size();i++){
							getFileSzie(filelist[(int) select.get(i)]);
						}
					}catch(RuntimeException e){
						//
					}
				}
			});
			for(int i=0;i<select.size();i++){
				type.append(getPostfix(filelist[(int) select.get(i)])+" , ");
			}
		}
		getSize.start();
		handler.post(runnable);
	}
	public long getFileSzie(File file){
		FileInputStream fis = null;
		File[] list;
		long byteSize=0;
		if(stopThread==true){throw new RuntimeException();}
		if(file.isDirectory()){//如果是文件夹
			try{
				list=file.listFiles();
				for(int i=0;i<list.length;i++){
					byteSize=byteSize+getFileSzie(list[i]);//遍历
				}
			}catch(Exception e){
				Log.d("读取文件", file.getName()+"不能读取");
			}
		}else{
			try {
				fis = new FileInputStream(file);
				byteSize=fis.available();
				fileByteSize+=byteSize;
			} catch (FileNotFoundException e) {		} 
			catch (IOException e) {		}
		}
		if(fis!=null){
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return byteSize;
	}
 	public String fileSizeToString(long byteSize){
		String size = "0 B";
		DecimalFormat df=new DecimalFormat("###.00");
		if(byteSize==0) return size;
		if(byteSize<1024){
			size=byteSize+" B";
		}else if(byteSize<1048576){
			size=df.format(byteSize/1024.0)+" KB";
		}else if(byteSize<1073741824){
			size=df.format(byteSize/1048576.0)+" MB";
		}else{
			size=df.format(byteSize/1073741824.0)+" GB";
		}
		return size;
	}
 	Runnable runnable=new Runnable() {
		@Override
		public void run() {
			TextView size=(TextView) attributesView.findViewById(R.id.size);
			size.setText(fileSizeToString(fileByteSize));
			if(getSize.isAlive()){
				handler.postDelayed(runnable, 1000);
				size.append("      loading...");
			}else{
				handler.removeCallbacks(runnable);
				fileByteSize=0;
			}
		}
	};
		
	public void refresh(){
		filelist = path.listFiles();
		filelist=groupbyname(filelist);
		mdata.clear();
	    for(int i=0;i<filelist.length;i++){
	        Map<String,Object> map=new HashMap<String,Object>();
	        if(filelist[i].isDirectory()){
	        	map.put("img", R.drawable.floder);
	        }else{
	        	map.put("img",R.drawable.file);
	        }
	       	map.put("name", filelist[i].getName());
	       	map.put("fileType", getPostfix(filelist[i]));
	       	mdata.add(map);
	    }
	    for(int i=0;i<filelist.length;i++){
			isCheck.put(""+i, false);
		}
		baseAdapter.notifyDataSetChanged();
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getTitle().toString()){
		case "重命名":
			rename();
		}
			
		return super.onMenuItemSelected(featureId, item);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("重命名");
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		refresh();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK&&checkBoxVisable==View.VISIBLE){
			checkBoxVisable=View.GONE;
			listView.setOnItemClickListener(browseState);
			listView.setOnItemLongClickListener(itemLongClickListener);
			for(int i=0;i<filelist.length;i++){
				isCheck.put(""+i, false);
			}
			CheckBox selectAll=(CheckBox) findViewById(R.id.selectAll);
			selectAll.setChecked(false);
			baseAdapter.notifyDataSetChanged();
			return false;
		}
		if(keyCode==KeyEvent.KEYCODE_BACK&&firstActivity==true&&checkBoxVisable==View.GONE){
			exit();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	public void exit(){
		if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
	}
}
